const {common: common} = require("../common/common");

var leader = require("../common/leader.js").leader;

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        origin: 2,
        //来源：1 接龙
        page_type: 1,
        //1:平台商品 2：团长自营店商品 即传入的type
        source: 1,
        //来源：1 接龙 2：视频
        page: 1,
        totalSize: 1,
        height: 0,
        loading: 0,
        showLoading: true,
        showPage: false,
        showGoodsList: false,
        choosePid: 0,
        chooseSubPid: 0,
        product_limit: 0,
        //0不限制
        second_index: 0,
        myleaderinfo: {},
        goodsList: [],
        selectIds: [],
        //选中商品id
        selectIds_pre: [],
        repeatB: false,
        room_id: "",
        sorts: [ {
            fieldName: "created_at",
            ifAsc: false
        } ],
        ifSelf: false,
        screenItems: [ {
            key: 0,
            name: "发布时间",
            active: true,
            fieldName: "created_at",
            ifAsc: false
        }, {
            key: 1,
            name: "商品单价",
            active: false,
            fieldName: "price",
            ifAsc: false
        }, {
            key: 2,
            name: "佣金",
            active: false,
            fieldName: "brokerage_price",
            ifAsc: false,
            video: 0,
            limit_goods: 0
        } ]
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad(options) {
        wx.setNavigationBarTitle({
            title: options.type != 1 ? "实物类商品库" : "平台商品库"
        });
        let selectIdss = options.selectIds ? JSON.parse(options.selectIds) : [];
        let selectIds = [];
        if (options.type == 1) {
            selectIdss.forEach(item => {
                selectIds.push(item.toString());
            });
        } else {
            selectIds = selectIdss;
        }
        console.log(options.origin);
        this.setData({
            page_type: options.type || 1,
            source: options.source || 1,
            selectIds: selectIds.length ? selectIds : [],
            //传入的selectIds
            selectIds_pre: selectIds.length ? selectIds : [],
            //传入的selectIds
            room_id: options.room_id || "",
            origin: options.origin || 2,
            //群接龙跳转时options.origin=='1',
            video: options.video || 0
        });
        if (this.data.video == 1) {
            this.getVideoLimit();
        }
        if (options.origin != "1") {
            this.setData({
                ifSelf: true
            });
        }
        console.log("------------------", options.origin);
        if (options.source == 1) {
            //来源接龙需要请求接龙设置
            this.getGragonSetting();
        }
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow() {
        //首次直接进入，拿openid
        if (app.globalData.user) {
            //如果直接拿到openid
            this.requestStart(app.globalData.user.openid);
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                this.requestStart(res.openid);
            });
        }
    },
    /**
   * 获取接龙设置
   */
    getGragonSetting: function() {
        common.request({
            endpoint: "group-solit/set-read",
            method: "post",
            data: {},
            success: res => {
                this.setData({
                    product_limit: res.extra.product_limit || 0
                });
            }
        });
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom() {},
    /**
   * 获取设备信息
   */
    getSystemInfo: function() {
        let that = this;
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    height: res.windowHeight,
                    isIos: res.system.includes("iOS")
                });
            }
        });
    },
    /**
   * 请求
   */
    requestStart: function(openid) {
        this.getSystemInfo();
        console.log(12);
        leader.getMyLeaderInfo_aync(openid, "").then(() => {
            this.getClass();
        });
    },
    /**
   * 获取分类列表
   */
    getClass: function() {
        let that = this;
        let url = ``;
        let params = {};
        if (that.data.page_type == 1) {
            url = "product/classification";
            params = {
                page_type: 1
            };
        } else if (that.data.page_type == 2) {
            url = that.data.origin == 1 ? "v1/Supermarket/product-category/first-category-plat" : "v1/Supermarket/product-category/first-category";
            params = {
                // business_id: that.data.myleaderinfo.leader_shop.shop_id
                business_id: that.data.ifSelf === true ? that.data.myleaderinfo.leader_shop.shop_id : 0
            };
        }
        common.request({
            endpoint: url,
            method: "post",
            data: params,
            success: res => {
                that.setData({
                    class: that.data.page_type == 1 ? res.extra.data : res.extra,
                    showPage: true,
                    goodsList: []
                });
                if (that.data.page_type == 1) {
                    let first_classfit = res.extra.data.map((item, index) => {
                        return item;
                    });
                    let second_classfit = res.extra.data.map((item, index) => {
                        return item.sub.map((i, j) => {
                            return i;
                        });
                    });
                    var pid = res.extra.data[0].id;
                    //优先请求链接中的一级分类>无分类
                                        that.setData({
                        first_classfit: first_classfit,
                        second_classfit: second_classfit,
                        choosePid: pid
                    });
                    //显示二级分类
                                        res.extra.data.forEach((item, index) => {
                        if (item.id == pid) {
                            that.setData({
                                subClasses: item.sub,
                                chooseSubPid: item.sub[0].id
                            });
                        }
                    });
                    if (that.data.page_type == 1) {
                        that.getPlatGoods(that.data.chooseSubPid);
                    }
                } else if (that.data.page_type == 2) {
                    if (that.data.class.length) {
                        that.setData({
                            choosePid: that.data.class.length ? that.data.class[0]["id"] : ""
                        });
                        that.getOwnSecondCate();
                    } else {
                        that.setData({
                            showLoading: false
                        });
                    }
                }
            }
        });
    },
    /**
   * 获取自营商品二级分类
   * @param {*} e 
   */
    getOwnSecondCate: function() {
        let that = this;
        if (that.data.class.length <= 0) {
            return false;
        }
        common.request({
            endpoint: that.data.origin == 1 ? "v1/Supermarket/product-category/second-category-plat" : "v1/Supermarket/product-category/second-category",
            method: "post",
            data: {
                business_id: that.data.ifSelf === true ? that.data.myleaderinfo.leader_shop.shop_id : 0,
                parent_id: that.data.choosePid
            },
            success: res => {
                if (res.code == 0) {
                    that.setData({
                        subClasses: res.extra,
                        chooseSubPid: res.extra.length ? res.extra[0]["id"] : ""
                    });
                    that.getOwnShopGoods();
                }
            }
        });
    },
    /**
  * 点击一级分类
  */
    chooseClass: function(e) {
        let that = this;
        if (that.data.repeatB) {
            return false;
        }
        that.setData({
            showLoading: true,
            noScroll: true,
            //该方法被触发时，scrollToLower不请求
            repeatB: true
        });
        let pid = e.currentTarget.dataset.id;
        that.setData({
            page: 1,
            goodsList: []
        });
        that.setData({
            choosePid: pid
        });
        if (that.data.page_type == 1) {
            let obj = that.data.class.find(item => item.id == pid);
            that.setData({
                subClasses: obj.sub,
                chooseSubPid: obj.sub[0].id
            });
            that.getPlatGoods(e.target.dataset.id);
        } else if (that.data.page_type == 2) {
            that.getOwnSecondCate();
        }
    },
    /**
  * 选择二级分类
  */
    chooseSubClasss(e) {
        let that = this;
        if (that.data.repeatB) {
            return false;
        }
        that.setData({
            page: 1,
            showLoading: true,
            goodsList: [],
            chooseSubPid: e.target.dataset.id,
            repeatB: true
        });
        if (that.data.page_type == 1) {
            that.getPlatGoods(e.target.dataset.id);
        } else if (that.data.page_type == 2) {
            that.getOwnShopGoods();
        }
    },
    /**
   * 记录input值
   * @param {*} e 
   */
    recordValue: function(e) {
        this.setData({
            pro_name: e.detail.value
        });
        if (!this.data.pro_name) {
            this.search();
        }
    },
    /**
   * 搜索
   * @param {e} 
   */
    search: function(e) {
        let that = this;
        if (that.data.repeatB) {
            return false;
        }
        that.setData({
            showLoading: true,
            page: 1,
            goodsList: [],
            repeatB: true
        });
        if (that.data.page_type == 1) {
            that.getPlatGoods();
        } else if (that.data.page_type == 2) {
            that.getOwnShopGoods();
        }
    },
    /**
   * 获取平台商品
   */
    getPlatGoods: function() {
        let that = this;
        let options = {
            leader_id_true: that.data.myleaderinfo.leader_id_true != -1 ? that.data.myleaderinfo.leader_id_true : -1,
            pid: that.data.chooseSubPid,
            page: that.data.page,
            rows: 10,
            pro_name: that.data.pro_name || "",
            source: that.data.source
        };
        common.request({
            endpoint: "product/class_product",
            method: "post",
            data: options,
            success: res => {
                if (res.code == 0) {
                    let result = res.extra;
                    let arr = that.data.page == 1 ? [] : that.data.goodsList;
                    // 非重复增加数据
                                        result.sub.forEach(item => {
                        var isExist = arr.find(e => e.id == item.id);
                        if (!isExist) {
                            arr.push(item);
                        }
                    });
                    this.setData({
                        showLoading: false,
                        totalSize: result.total,
                        goodsList: arr,
                        page: that.data.page + 1,
                        repeatB: false
                    });
                }
            }
        });
    },
    /**
   * 获取自营店商品
   * @param {*} e 
   */
    getOwnShopGoods: function() {
        let that = this;
        if (that.data.page == 1) {
            that.setData({
                goodsList: []
            });
        }
        common.request({
            endpoint: that.data.origin == 1 ? "v1/Supermarket/product-plat" : "v1/Supermarket/product",
            method: "post",
            data: {
                business_id: that.data.ifSelf === true ? that.data.myleaderinfo.leader_shop.shop_id : 0,
                category_second_id: that.data.chooseSubPid,
                parent_id: that.data.choosePid,
                page: that.data.page,
                pro_name: that.data.pro_name,
                sorts: that.data.sorts
            },
            success: res => {
                let arr = that.data.page == 1 ? [] : that.data.goodsList;
                // let arr = that.data.goodsList;
                // res.extra.rows.forEach(item => {
                //   let obj = {
                //     id: item.id,
                //     img: item.face,
                //     title: item.name,
                //     price: item.price,
                //     all_stock_num: item.stock,
                //     except_brokerage: item.except_brokerage
                //   }
                //   arr.push(obj)
                // })
                // 非重复增加数据
                                res.extra.rows.forEach(item => {
                    var isExist = arr.find(e => e.id == item.id);
                    if (!isExist) {
                        let obj = {
                            id: item.id,
                            img: item.face,
                            title: item.name,
                            price: item.price,
                            all_stock_num: item.stock,
                            except_brokerage: item.except_brokerage,
                            max_except_brokerage: item.max_except_brokerage,
                            max_price: item.max_price
                        };
                        arr.push(obj);
                    }
                });
                // console.log(arr)
                                that.setData({
                    showLoading: false,
                    totalSize: res.extra.total,
                    goodsList: arr,
                    page: that.data.page + 1,
                    repeatB: false
                });
                // console.log(that.data.showLoading)
                        }
        });
    },
    /**
   * 选择商品
   */
    selectGood: function(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        let item = e.currentTarget.dataset.item;
        if (item.all_stock_num == 0) {
            wx.showToast({
                icon: "error",
                title: "售罄商品不可选！"
            });
            return false;
        }
        let arr = that.data.selectIds;
        let index = arr.findIndex(item => item == id);
        if (index == -1) {
            if (that.data.source == 1 && that.data.product_limit > 0 && that.data.selectIds.length >= that.data.product_limit && that.data.room_id == "") {
                wx.showModal({
                    title: "提示",
                    content: `最多可添加${that.data.product_limit}件商品！`,
                    showCancel: false,
                    complete: res => {}
                });
                return false;
            }
            if (that.data.video == 1 && that.data.video_limit > 0 && that.data.selectIds.length >= that.data.video_limit) {
                wx.showModal({
                    title: "提示",
                    content: `最多可添加${that.data.video_limit}件商品！`,
                    showCancel: false,
                    complete: res => {}
                });
                return false;
            }
            arr.push(id);
        } else {
            arr.splice(index, 1);
        }
        that.setData({
            selectIds: arr
        });
    },
    /**
   * 滚动加载
   */
    scrollToLower: function() {
        let that = this;
        if (that.data.goodsList.length < that.data.totalSize) {
            if (that.data.page_type == 1) {
                that.getPlatGoods();
            } else if (that.data.page_type == 2) {
                that.getOwnShopGoods();
            }
        }
    },
    /**
   * 确认选择
   */
    confirmSelect: function() {
        let that = this;
        if (!that.data.selectIds.length) {
            wx.showToast({
                icon: "none",
                title: "请选择商品！"
            });
            return false;
        }
        if (that.data.room_id != "") {
            that.importGoods();
        } else {
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage) {
                prevPage.setData({
                    selectIds: that.data.selectIds,
                    selectIds_pre: that.data.selectIds
                });
                wx.navigateBack();
            }
        }
    },
    //导入商品
    importGoods: common.throttle(function(e) {
        let that = this;
        let arr = [];
        that.data.selectIds.forEach(item => {
            let data = {
                product_id: item,
                source: 2
            };
            arr.push(data);
        });
        wx.showLoading({
            title: "正在导入"
        });
        common.request({
            endpoint: "LiveShopping/manage/product-import",
            method: "post",
            data: {
                room_id: that.data.room_id,
                products: arr
            },
            success: res => {
                wx.showToast({
                    title: "导入成功"
                });
                const pages = getCurrentPages();
                const prevPage = pages[pages.length - 2];
                prevPage.getData();
                wx.navigateBack();
            },
            fail: err => {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            },
            complete: res => {
                wx.hideLoading();
            }
        });
    }, 3e3),
    clickScreen(e) {
        let items = this.data.screenItems;
        items.map((item, index) => {
            if (item.key == e.currentTarget.dataset.key) {
                if (item.active === true) {
                    if (item.ifAsc === true) {
                        item.ifAsc = false;
                    } else {
                        item.ifAsc = true;
                    }
                } else {
                    item.active = true;
                    item.ifAsc = false;
                }
            } else {
                item.active = false;
                item.ifAsc = false;
            }
        });
        let obj = {
            fieldName: items[e.currentTarget.dataset.key]["fieldName"],
            ifAsc: items[e.currentTarget.dataset.key]["ifAsc"]
        };
        this.setData({
            screenItems: items,
            sorts: [ obj ]
        });
        this.search();
        console.log(this.data.screenItems[e.currentTarget.dataset.key]);
    },
    clickFilter() {
        if (this.data.ifSelf === false) {
            this.setData({
                ifSelf: true
            });
            this.search();
        } else {
            this.setData({
                ifSelf: false
            });
            this.search();
        }
    },
    //获取视频购商品数量限制
    getVideoLimit() {
        common.request({
            endpoint: "/Video/manage/set-read",
            data: {},
            success: res => {
                this.setData({
                    video_limit: res.extra.limit_goods || 0
                });
            }
        });
    }
});